package com.file.system.plugin.dict;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.file.system.entity.basic.RedisKey;
import com.file.system.entity.system.WebDictionary;
import com.file.system.entity.system.WebDictionaryVal;
import com.file.system.service.system.IWebDictionaryService;
import com.file.system.service.system.IWebDictionaryValService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.util.ObjectUtil.*;


@Component
public class DictAspect extends JsonSerializer<String> {

    @Autowired
    private IWebDictionaryService iWebDictionaryService;
    @Autowired
    private IWebDictionaryValService iWebDictionaryValService;

    private static List<WebDictionary> dicList;
    private static List<WebDictionaryVal> valList;

    // 序列化
    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
        try {
            // 获取字段名称及所在类
            String fieldName = jsonGenerator.getOutputContext().getCurrentName();
            Class<?> declaringClass = jsonGenerator.getOutputContext().getCurrentValue().getClass();

            // 获取@DictNew注解的值
            Field field = declaringClass.getDeclaredField(fieldName);
            field.setAccessible(true); // 设置字段可访问
            Dict dictNewAnnotation = field.getAnnotation(Dict.class);
            String dictNewValue = dictNewAnnotation.value();
            String text = translateDictValue(dictNewValue, value);

            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("value", value); // 写入字段值
            jsonGenerator.writeStringField("text", text); // 写入字段名称
            jsonGenerator.writeEndObject();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 翻译字典值
     */
    private String translateDictValue(String dictType, String val) {
        if (StrUtil.isEmpty(val)) {
            return null;
        }


        dicList = iWebDictionaryService.list(new QueryWrapper<WebDictionary>()
                .eq("a.is_del", 0)
                .eq("a.code", dictType)
        );

        WebDictionary webDictionary = dicList.stream().filter(l -> l.getCode().equals(dictType)).findFirst().orElse(null);
        if (webDictionary == null) {
            return null;
        }

        valList = iWebDictionaryValService.list(new QueryWrapper<WebDictionaryVal>()
                .eq("a.is_del", 0)
                .eq("a.fk_dictionary_id", webDictionary.getId())
        );

        // 如果字典值列表不为空，且val不为空
        if (isNotNull(valList) && !valList.isEmpty() && isNotEmpty(val)) {
            // 将val以逗号分隔
            String[] vals = val.split(",");
            StringBuilder sb = new StringBuilder();
            // 遍历vals
            for (String str : vals) {
                // 如果sb的长度大于0，则添加逗号
                if (sb.length() > 0) {
                    sb.append(",");
                }
                // 过滤字典值列表，获取与str匹配的值
                List<WebDictionaryVal> dictionaryValList = filterDictionaryValues(valList, str);
                // 如果匹配到的值不为空
                if (!dictionaryValList.isEmpty()) {
                    // 将匹配到的值添加到sb中
                    sb.append(dictionaryValList.get(0).getName());
                }
            }
            // 返回sb
            return sb.toString();
        }
        // 否则返回null
        return null;
    }


    /**
     * 匹配字典值
     */
    private List<WebDictionaryVal> filterDictionaryValues(List<WebDictionaryVal> valList, String str) {
        // 过滤字典值
        return valList.stream()
                // 过滤出等于str的值
                .filter(l -> equal(str, l.getVal()))
                // 将过滤后的值收集到新的列表中
                .collect(Collectors.toList());
    }


}
